/*
 * Copyright (c) 2015-2018 Sfkj Science And Technology Co.,Ltd.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Sfkj Science And Technology Co.,Ltd.
 * ("Confidential Information").You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sfkj.
 */
package com.sfkj.walk.web;

import com.google.common.base.Throwables;
import com.sfkj.walk.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@ControllerAdvice
public class DefaultExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody
    Map<String, Object> handleException(Exception ex) {
        String message = Throwables.getRootCause(ex).getMessage();
        log.warn("Http Status: " + HttpStatus.INTERNAL_SERVER_ERROR + " : " + message);
        log.error("Exception", ex);
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", new Date());
        map.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
        map.put("error", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
        map.put("exception", ex);
        map.put("message", message);
        return map;
    }

    @ExceptionHandler({
            SystemException.class, IllegalArgumentException.class, IllegalStateException.class
    })
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody
    Map<String, Object> handleRuntimeException(Throwable ex) {
        String message = Throwables.getRootCause(ex).getMessage();
        log.warn("Http Status: " + HttpStatus.INTERNAL_SERVER_ERROR + " : " + message);
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", new Date());
        map.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
        map.put("error", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
        map.put("message", message);
        return map;
    }

}
